package main

import (
	"context"
	"flag"
	"fmt"
	"net"

	"gozero-microservices/gateway-api/internal/config"
	"gozero-microservices/gateway-api/internal/handler"
	"gozero-microservices/gateway-api/internal/middlewares"
	"gozero-microservices/gateway-api/internal/svc"

	"github.com/dtm-labs/client/workflow"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/trace"
	"github.com/zeromicro/go-zero/rest"
	"google.golang.org/grpc"
)

var configFile = flag.String("f", "etc/app.yaml", "the config file")

func main() {
	var env string
	// 运行环境
	flag.StringVar(&env, "env", "dev", "运行环境")
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	// 启用追踪代理
	trace.StartAgent(c.Telemetry)

	// 设置环境变量
	c.Env = env

	// 初始化日志
	logx.MustSetup(c.CustomLog)
	// 输出当前环境
	logx.Info(context.Background(), " current environment: "+env)

	defer logx.Close()

	// 创建服务
	server := rest.MustNewServer(c.RestConf)

	// 注册全局 JSON 中间件
	server.Use(middlewares.GlobalJsonMiddleware)

	defer server.Stop()

	// 创建服务上下文
	ctx := svc.NewServiceContext(c)

	// 注册处理器
	handler.RegisterHandlers(server, ctx)

	// 使用单级限流器[PeriodLimiter、TokenLimiter]
	switch ctx.Config.LimiterConf.Mode {
	case "period":
		server.Use(middlewares.PeriodLimiterMiddleware(ctx))
	case "token":
		server.Use(middlewares.TokenLimiterMiddleware(ctx))
	}

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)

	// 启动grpc服务
	startGrpcServer(c)

	// 启动服务
	server.Start()
}

/**
 * 启动grpc服务
 *
 * @param config.Config c --------------------------必传
 * @author huwl
 * @date 2025/10/27 09:27:46
 */
func startGrpcServer(c config.Config) {
	// 实例化gRPC服务
	srv := grpc.NewServer()

	// 获取dtm grpc服务地址
	dtmGrpcServerUrl := ""
	switch c.Env {
	case "dev":
		dtmGrpcServerUrl = c.DtmConf.Dev.GrpcServer
	case "test":
		dtmGrpcServerUrl = c.DtmConf.Test.GrpcServer
	case "prod":
		dtmGrpcServerUrl = c.DtmConf.Prod.GrpcServer
	}
	go func() {
		// tcp协议监听指定端口号
		lis, err := net.Listen("tcp", c.GrpcHost+fmt.Sprintf(":%d", c.GrpcPort))
		if err != nil {
			logx.Error("Failed to listen: " + err.Error())
		}

		fmt.Printf("grpc server listening at %s:%d...\n", c.GrpcHost, c.GrpcPort)

		// 启动grpc服务
		if err := srv.Serve(lis); err != nil {
			logx.Error("failed to grpc serve: " + err.Error())
		}
	}()

	// 初始化注册dtm 服务
	workflow.InitGrpc(dtmGrpcServerUrl, c.GrpcHost+fmt.Sprintf(":%d", c.GrpcPort), srv)
}
